﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ALinq.Access;
using ALinq.Mapping;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NorthwindDemo;

namespace TestProject
{
    [TestClass]
    public class ColumnMappingTest
    {
        private const string CategoryTableName = "Categories";
        private const string ProdcutTableName = "Products";

        class NorthwindMappingSource : FluentMappingSource
        {
            public NorthwindMappingSource(Action<DatabaseMapping<NorthwindDatabase>> func = null)
            {
                Map<NorthwindDatabase>(mapping =>
                {
                    mapping.ProviderType = typeof(AccessDbProvider);
                    mapping.Table(o => o.Categories, CategoryTableName)
                           .PrimaryKey(o => o.CategoryID)
                           .Column(o => o.CategoryName)
                           .Column(o => o.Description)
                           .Column(o => o.Picture)
                           .Association(o => o.Products, o => o.CategoryID, o => o.CategoryID);

                    mapping.Table(o => o.Products, ProdcutTableName)
                           .PrimaryKey(o => o.ProductID)
                           .Column(o => o.ProductName)
                           .Column(o => o.CategoryID)
                           .Association(o => o.Category, o => o.CategoryID, o => o.CategoryID);

                    if (func != null)
                        func(mapping);
                });
            }
        }

        [TestMethod]
        public void ModifyColumnName()
        {
            var mappingSource = new NorthwindMappingSource();
            var model = mappingSource.GetModel(typeof(NorthwindDatabase));
            var categoryTable = model.GetTable(typeof(Category));
            var categoryNameMember = categoryTable.RowType.DataMembers.Single(o => o.Name == "CategoryName");
            var columnName = categoryNameMember.MappedName;

            string newColumnName = "New" + columnName;
            mappingSource = new NorthwindMappingSource(mapping =>
            {
                mapping.Table(o => o.Categories)
                       .Column(o => o.CategoryName, o => { o.Name = newColumnName; });
            });

            model = mappingSource.GetModel(typeof(NorthwindDatabase));
            categoryTable = model.GetTable(typeof(Category));
            categoryNameMember = categoryTable.RowType.DataMembers.Single(o => o.Name == "CategoryName");
            columnName = categoryNameMember.MappedName;
            Assert.AreEqual(newColumnName, columnName);
        }
    }
}
